package com.itheima.appserver.service;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.appserver.excepiton.BusinessException;
import com.itheima.appserver.excepiton.ErrorResult;
import com.itheima.appserver.interceptor.UserThreadLocal;
import com.itheima.commons.constants.Constants;
import com.itheima.commons.pojo.domain.UserInfo;
import com.itheima.commons.pojo.mongo.LogPeach;
import com.itheima.commons.pojo.mongo.Peach;
import com.itheima.commons.utils.UploadSounds;
import com.itheima.commons.vo.reception.PeachVo;
import com.itheima.dubbo.interfaces.LogPeachApi;
import com.itheima.dubbo.interfaces.PeachBlossomApi;
import com.itheima.dubbo.interfaces.UserInfoApi;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.time.Duration;
import java.util.Date;
import java.util.List;

@Service
public class PeachBlossomService {
    @Reference
    PeachBlossomApi peachBlossomApi;
    @Reference
    LogPeachApi logPeachApi;
    @Reference
    UserInfoApi userInfoApi;
    @Autowired
    RedisTemplate<String,String> redisTemplate;

    public void uploadSounds(MultipartFile soundsFile) {
        //创建redis语音键(传音只能10次)
        //在redis里设置一个唯一的缓存键，根据当天的时间设置，并且根据下面的清除缓存设置清除
        Date date = new Date();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        String dateTime = simpleDateFormat.format(date);
        String key= Constants.SEND_SOUND_KEY+"_"+dateTime+"_"+UserThreadLocal.getUserId();

        //先从redis中获取key
        String value = redisTemplate.opsForValue().get(key);
        if (value==null){
            //如果为空说明没有发送过   设置持续时间一天
            redisTemplate.opsForValue().set(key,"9", Duration.ofDays(1));
        }else if(value.equals("0")){
            //说明使用次数已经到了10次
            throw new BusinessException(ErrorResult.fasongcishuchaoxian());
        }else {
            // 访问一次消耗一次
            redisTemplate.opsForValue().decrement(key);
        }
        //获取文件后缀名
        String suffix = StrUtil.subAfter(soundsFile.getOriginalFilename(), ".", true);
        //将语音上传到服务器 返回语音存放地址地址
        try {
            String soundUrl = UploadSounds.uploadSounds(soundsFile.getBytes(), suffix);

            // 拼凑对象，保存到数据库
            Peach peach = new Peach();
            peach.setId(new ObjectId());
            peach.setSoundUrl(soundUrl);
            peach.setRemainingTimes(Convert.toInt(redisTemplate.opsForValue().get(key)));
            peach.setUserId(UserThreadLocal.getUserId());
            peach.setCreate(new Date(System.currentTimeMillis()));
            peach.setUpdate(peach.getCreate());


            peachBlossomApi.addPeach(peach);
        } catch (IOException e) {
            throw new BusinessException(ErrorResult.soundUploadError());
        }

    }

    public PeachVo receiveSound() {
        //判断接收次数
        Date date = new Date();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        String dateTime = simpleDateFormat.format(date);
        String key = Constants.GET_SOUND_KEY + "_" + dateTime + "_" + UserThreadLocal.getUserId();

        String count = redisTemplate.opsForValue().get(key);
        if (count == null) {
            //没有接受过，设置接收键
            redisTemplate.opsForValue().set(key, "9", Duration.ofDays(1));
        } else if (count.equals("0")) {
            //已经接收过10次
            throw new BusinessException(ErrorResult.jieshoucishuchaoxian());
        } else {
            //访问一次，消耗一次
            redisTemplate.opsForValue().decrement(key);
        }
        //先获取到除了自己所有的发送过语音的用户
        List<Peach> allusers = peachBlossomApi.findAllUrlIsNotMine(UserThreadLocal.getUserId());
        if (CollUtil.isEmpty(allusers)) {
            throw new BusinessException(ErrorResult.notFindSounds());
        }
        PeachVo peachVo = new PeachVo();
        LogPeach lp = new LogPeach();

        // 获取自己接收过的所有语音
        List<LogPeach> allById = logPeachApi.findAllById(UserThreadLocal.getUserId());
        //  判断自己是否接受过语音
        if (CollUtil.isEmpty(allById)) {
            //如果没有
            for (Peach alluser : allusers) {
                UserInfo userInfoByUserId = userInfoApi.findUserInfoByUserId(alluser.getUserId());
                //获取当前用户的 信息
                Peach userById = peachBlossomApi.findUserById(UserThreadLocal.getUserId());
                //拼凑vo返回对象
                peachVo.setId(Convert.toInt(userInfoByUserId.getUserId()));
                peachVo.setAvatar(userInfoByUserId.getLogo());
                peachVo.setNickname(userInfoByUserId.getNickName());
                peachVo.setGender(userInfoByUserId.getSex() == 1 ? "man" : "woman");
                peachVo.setSoundUrl(alluser.getSoundUrl());
                peachVo.setRemainingTimes(Convert.toInt(redisTemplate.opsForValue().get(key)));
                peachVo.setAge(userInfoByUserId.getAge());


                //将获取到的url添加到LogPeach中
                lp.setId(new ObjectId());
                lp.setUserId(Convert.toInt(UserThreadLocal.getUserId()));
                lp.setReceiveSound(alluser.getSoundUrl());
                logPeachApi.addlog(lp);
                break;
            }
        } else {
            //遍历所有的语音，和自己接收到的所有语音是否相等
            for (Peach alluser : allusers) {
                for (LogPeach logPeach : allById) {
                    if (!alluser.getSoundUrl().equals(logPeach.getReceiveSound())) {
                        //  不相等  查询该语音用户的信息
                        UserInfo userInfoByUserId = userInfoApi.findUserInfoByUserId(alluser.getUserId());
                        //获取当前用户的 信息
                        Peach userById = peachBlossomApi.findUserById(UserThreadLocal.getUserId());
                        //拼凑vo返回对象
                        peachVo.setId(Convert.toInt(userInfoByUserId.getUserId()));
                        peachVo.setAvatar(userInfoByUserId.getLogo());
                        peachVo.setNickname(userInfoByUserId.getNickName());
                        peachVo.setGender(userInfoByUserId.getSex() == 1 ? "man" : "woman");
                        peachVo.setSoundUrl(alluser.getSoundUrl());
                        peachVo.setRemainingTimes(Convert.toInt(redisTemplate.opsForValue().get(key)));
                        peachVo.setAge(userInfoByUserId.getAge());

                        //将获取到的url添加到LogPeach中
                        lp.setId(new ObjectId());
                        lp.setUserId(Convert.toInt(UserThreadLocal.getUserId()));
                        lp.setReceiveSound(alluser.getSoundUrl());
                        logPeachApi.addlog(lp);
                    }
                    break;
                }
                break;
            }
        }
        return peachVo;
    }
}
